import  pymysql
from dbutils.pooled_db import PooledDB
from Case.python_ui.Test_data.common_data import Commondata
#class DoMysql(object):

class DoMysql(object):


    def __init__(self,cmdopt):
        self.cmdopt=cmdopt


    def databases(self):
        self.db_config=Commondata.db_config[self.cmdopt]
        self.db_config['cursorclass']=pymysql.cursors.DictCursor
        database_list = self.db_config['database']
        max_conn_list = self.db_config['maxconnections']
        self.databases = {
            self.cmdopt: []
        }
        for i in database_list:
            db_config_new = self.db_config.copy()
            db_config_new["database"] = i
            db_config_new["maxconnections"] = max_conn_list[database_list.index(i)]
            database_entry = {
                "pool": PooledDB(pymysql, **db_config_new),
                "object": DoMysql(self.cmdopt),
                "database": i
            }
            self.databases[self.cmdopt].append(database_entry)
        return self.databases




    def  do_mysql(self,sql,pool,state='all'):
        #建立数据库连接池
        connect=pool.connection()
        cursor=connect.cursor()
        cursor.execute(sql)
        connect.commit()
        if state == 1:
            res = cursor.fetchone()  # 元祖，针对一条数据
        else:
            res = cursor.fetchall()  # 列表，针对多行数据，列表嵌套元祖

        connect.commit()
        #connect.close()
        print(res)
        return res









